package com.example.administrator.student4;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.student4.Adapter.StudentAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * Created by Administrator on 2016/12/11.
 */
public class Student extends Activity {
    ListView lv;
    String path = "http://10.0.2.2:8080/andorid/student?";
    JSONArray array;
    MyHandler myHandler;
    TextView add;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.student);
        lv  = (ListView) findViewById(R.id.studentinfo);
        add = (TextView) findViewById(R.id.add);
        myHandler = new MyHandler();
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Student.this,StudentDetail.class);
                startActivity(intent);
            }
        });
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(path+"request=findall");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.connect();
                    if(connection.getResponseCode() == 200){
                        InputStream is = connection.getInputStream();
                        array = WebUtil.ioToJsonArray(is);
                    }
                    myHandler.sendEmptyMessage(0x111);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x111){
                StudentAdapter adapter = new StudentAdapter(Student.this,array);
                lv.setAdapter(adapter);
            }
        }
    }
}
